package com.ruoyi.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.auth.NotLoginException;
import com.ruoyi.common.core.utils.JwtUtils;
import com.ruoyi.common.core.utils.ip.IpUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.user.domain.dto.UserDTO;
import com.ruoyi.user.domain.entity.User;
import com.ruoyi.user.domain.request.LoginRequest;
import com.ruoyi.user.domain.vo.LoginVo;
import com.ruoyi.user.mapper.UserMapper;
import com.ruoyi.user.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyf
 * @since 2024-12-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisService redisService;

    @Override
    public LoginVo login(LoginRequest loginRequest) {
        User user = this.lambdaQuery()
                        .eq(User::getUserName, loginRequest.getUserName())
                        .eq(User::getPassword, loginRequest.getPassword()).one();
        if(user == null){
            throw new NotLoginException("账号密码错误");
        }
        String token = IdUtils.fastUUID();
        Long userId = user.getId();
        String userName = user.getUserName();

        // 根据uuid将loginUser缓存
        LoginUser loginUser = new LoginUser();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + CacheConstants.EXPIRATION * 60 * 1000);
        redisService.setCacheObject(CacheConstants.LOGIN_TOKEN_KEY + token,loginUser, CacheConstants.EXPIRATION, TimeUnit.MINUTES);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
        // 获取Jwt加密后的token
        String accessToken = JwtUtils.createToken(claimsMap);

        // 封装返回类
        UserDTO userInfo = BeanUtil.copyProperties(user, UserDTO.class);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(accessToken);
        loginVo.setUserInfo(userInfo);
        return loginVo;
    }
}
